<template>
  <div>
    <Row style="align-items: flex-start;margin-bottom:5px;display:block">
      <Col :lg="10" :xs="22" offset="0.5">
        <vxe-toolbar :refresh="{ query: reload }" print v-if="isUpdate">
          <template #buttons>
            <vxe-button size="mini" status="primary" @click="impotEvent"
              >导入</vxe-button
            >
            <vxe-button size="mini" status="primary" @click="exportFile"
              >导出</vxe-button
            >
            <vxe-button size="mini" status="primary" @click="addRow"
              >新增</vxe-button
            >
            <vxe-button size="mini" status="danger" @click="delRow"
              >删除</vxe-button
            >
            <vxe-button size="mini" @click="saveData">保存</vxe-button>
          </template>
        </vxe-toolbar>
        <vxe-table
          class="sortable-row-demo"
          ref="xTable"
          height="400"
          border
          :edit-rules="validRules"
          highlight-hover-row
          show-overflow
          :data="tablePage.listPage"
          :print-config="{}"
          :export-config="{
            filename: filename(),
            columnFilterMethod: filterExport1,
            type: 'cvs'
          }"
          :loading="loading"
          :edit-config="{ trigger: 'click', mode: 'cell', enabled: isUpdate  }"
        >
          <vxe-column v-if="isUpdate" type="checkbox" width="60"></vxe-column>
          <vxe-column v-if="isUpdate" width="60">
            <template #default>
              <span class="drag-btn">
                <i class="vxe-icon--menu"></i>
              </span>
            </template>
            <template #header>
              <vxe-tooltip
                v-model="showHelpTip1"
                content="按住后可以上下拖动排序！"
                enterable
              >
                <i
                  class="vxe-icon--question"
                  @click="showHelpTip1 = !showHelpTip1"
                ></i>
              </vxe-tooltip>
            </template>
          </vxe-column>
          <vxe-column
            field="inputSpeed"
            title="输入转速(rpm)"
            :edit-render="{ name: 'input' }"
          ></vxe-column>
          <vxe-column
            field="unloadLoss"
            title="空载损失(kW)"
            :edit-render="{ name: 'input' }"
          ></vxe-column>
          <vxe-column
            field="loadLossCoefficient"
            title="负载损失系数(%)"
            :edit-render="{ name: 'input' }"
          ></vxe-column>
          <vxe-column
            field="gear"
            title="挡位"
            :edit-render="{ name: 'input' }"
          ></vxe-column>
        </vxe-table>
        <vxe-pager
          :current-page="tablePage.currentPage"
          :page-size="tablePage.pageSize"
          :total="tablePage.totalResult"
          :layouts="[
            'PrevPage',
            'JumpNumber',
            'NextPage',
            'FullJump',
            'Sizes',
            'Total'
          ]"
          @page-change="handlePageChange"
        >
        </vxe-pager>
      </Col>
      <Col :lg="12" :xs="22" offset="0.5">
        <div style="height:250px;margin-bottom: 30px;" id="a"></div>
        <div style="height:250px;" id="b"></div>
      </Col>
    </Row>
  </div>
</template>

<script>
import { gearboxEfficiencyApi } from "@/api/gearbox-efficiency";
import { gearboxShiftApi } from "@/api/gearbox-shift";
import XLSX, { WorkSheet } from "xlsx";
import Sortable from "sortablejs";
export default {
  name: "ProductivenessMap",
  components: {},
  props: {
    gearboxId: {
      type: Number
    },
    isUpdate: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      showHelpTip1: false,
      sortable1: null,
      tableData: [], // 表格列表数据
      tablePage: {
        currentPage: 1,
        pageSize: 10,
        totalResult: 0,
        listPage: []
      },
      loading: false,
      validRules: {
        inputSpeed: [
          { pattern: "^[0-9]+.?[0-9]*$", message: "请输入数字类型" }
        ],
        unloadLoss: [
          { pattern: "^[0-9]+.?[0-9]*$", message: "请输入数字类型" }
        ],
        loadLossCoefficient: [
          { pattern: "^[0-9]+.?[0-9]*$", message: "请输入数字类型" }
        ],
        gear: [{ pattern: "^[0-9]+.?[0-9]*$", message: "请输入数字类型" }]
      }
    };
  },
  watch: {
    /// 深度监听，可监听到对象、数组的变化  (table数据变化时，渲染echart)
    tableData: {
      handler(newVal, oldVal) {
        this.renderEchart();
      },
      deep: true // true 深度监听
    }
  },
  filters: {},
  created() {},
  mounted() {
    // 初始化数据
    this.initData();

    // 行拖动
    this.rowDrop();
  },
  methods: {
    rowDrop() {
      this.$nextTick(() => {
        const xTable = this.$refs.xTable;
        this.sortable1 = Sortable.create(
          xTable.$el.querySelector(".body--wrapper>.vxe-table--body tbody"),
          {
            handle: ".drag-btn",
            onEnd: ({ newIndex, oldIndex }) => {
              const currRow = this.tableData.splice(oldIndex, 1)[0];
              this.tableData.splice(newIndex, 0, currRow);
            }
          }
        );
      });
    },

    reRenderTable() {
      const newData = this.tablePage.listPage;
      this.tablePage.listPage = [];
      setTimeout(() => {
        this.tablePage.listPage = newData;
      }, 100);
    },
    filename() {
      return (
        "效率MAP曲线" +
        new Date(+new Date() + 8 * 3600 * 1000)
          .toJSON()
          .substr(0, 19)
          .replace("T", "")
          .replaceAll("-", "")
          .replaceAll(":", "")
      );
    },
    exportFile() {
      this.$refs.xTable.exportData({ type: "csv" });
    },
    filterExport1(data) {
      // 返回false 就是导出不显示
      if (!data.column.title) return false;
      if (data.column.type == "checkbox") return false;
      return true;
    },

    // 导入
    impotEvent() {
      this.$refs.xTable
        .readFile({
          types: ["xls", "xlsx", "csv"]
        })
        .then(params => {
          debugger;
          const { files } = params;
          const fileReader = new FileReader();
          fileReader.onload = ev => {
            const data = ev.target.result;
            const workbook = XLSX.read(data, { type: "binary" });
            const csvData = XLSX.utils.sheet_to_csv(workbook.Sheets.Sheet1);
            const tableData = [];
            console.log("解析的输入：");
            // 解析数据csvData
            csvData.split("\n").forEach((vRow, index) => {
              if (index == 0) {
                return;
              }
              if (vRow) {
                const vCols = vRow.split(",");
                const item = {};
                vCols.forEach((val, cIndex) => {
                  if (cIndex == 0) {
                    item["inputSpeed"] = val;
                  } else if (cIndex == 1) {
                    item["unloadLoss"] = val;
                  } else if (cIndex == 2) {
                    item["loadLossCoefficient"] = val;
                  } else if (cIndex == 3) {
                    item["gear"] = val;
                  }
                  item["index"] = Number(
                    Math.random()
                      .toString()
                      .substr(2, 10) + Date.now()
                  ).toString(36);
                });
                tableData.push(item);
              }
            });
            this.tableData = tableData;
            this.findList();
          };
          fileReader.readAsBinaryString(files[0]);
        });
    },

    // 刷新表格
    reload() {
      const $table = this.$refs.xTable;
      // 清除所有状态
      $table.clearAll();
      // 初始化数据
      this.initData();
    },

    // 翻页
    handlePageChange({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage;
      this.tablePage.pageSize = pageSize;
      this.findList();
    },

    findList() {
      // 总数据
      this.tablePage.totalResult = this.tableData.length;
      this.tablePage.listPage = this.tableData.slice(
        (this.tablePage.currentPage - 1) * this.tablePage.pageSize,
        this.tablePage.currentPage * this.tablePage.pageSize
      );
    },

    exportExcel1() {
      const workBook = XLSX.utils.table_to_book(
        this.$refs.xTable.$el.querySelector(".body--wrapper>.vxe-table--body")
      );
      XLSX.writeFile(workBook, "效率MAP.xlsx");
    },
    /// /////////////////////////////////////////第一个曲线 start
    /**
     * @desc 渲染echart--变速箱效率MAP
     * @sicne 2021/11/21
     */
    renderEchart() {
      // 获取到没有重复的挡位， 然后根据挡位生成n条曲线
      let gears = [];
      this.tableData.forEach(item => {
        if (item.gear && gears.indexOf(item.gear) == -1) gears.push(item.gear);
      });
      // 按照挡位升序
      gears.sort(function(a, b) {
        return a - b;
      });

      // 生成挡位名称
      const gearNames = gears.map(item => item + "挡");

      const series = [];

      const series1 = [];
      // 生成[x, y]坐标轴
      gears.forEach(gear => {
        // 转速，空载损失
        const unloadLosss = [];
        let tempTableData = [...this.tableData];
        tempTableData.sort((a, b) => a.inputSpeed - b.inputSpeed); // 排序
        tempTableData
          .filter(item => {
            return item.gear == gear;
          })
          .forEach(item => {
            const temp = [];
            temp.push(item.inputSpeed);
            temp.push(item.unloadLoss);
            unloadLosss.push(temp);
          });

        // 转速，负载损失
        const loadLossCoefficients = [];
        let tempTableData2 = [...this.tableData];
        tempTableData2.sort((a, b) => a.inputSpeed - b.inputSpeed); // 排序
        tempTableData2
          .filter(item => {
            return item.gear == gear;
          })
          .forEach(item => {
            const temp = [];
            temp.push(item.inputSpeed);
            temp.push(item.loadLossCoefficient);
            loadLossCoefficients.push(temp);
          });

        // 转速，空载损失----曲线
        series.push({
          id: "a" + gear,
          name: gear + "挡",
          type: "line",
          smooth: true,
          symbolSize: 5,
          data: unloadLosss
        });

        series1.push({
          id: "a" + gear,
          name: gear + "挡",
          type: "line",
          smooth: true,
          symbolSize: 5,
          data: loadLossCoefficients
        });
      });

      const option = {
        title: {
          text: "空载损失MAP"
        },
        tooltip: {
          trigger: "item",
          formatter: function(item) {
            let str = "";
            str += `挡位：${item.seriesName}<br/>转速：${item.data[0]}<br/>空载损失：${item.data[1]}`;
            str += "<br/><br/>";
            return str;
          }
        },
        legend: {
          x: "right",
          data: gearNames,
          textStyle: {
            fontsize: 5
          }
        },
        grid: {
          left: "10%",
          right: "4%",
          bottom: "8%",
          containLabel: true
        },

        xAxis: {
          type: "value",
          name: "输入转速(rpm)",
          nameLocation: "center",
          axisLine: { onZero: false },
          nameTextStyle: {
            padding: [0, 0, -25, 0],
            verticalAlign: "bottom"
          }
        },
        yAxis: [
          {
            name: "空载损失(kw)",
            axisLine: {
              lineStyle: {
                color: "#102b6a"
              },
              show: true
            },
            type: "value",
            position: "left",
            splitLine: {
              show: false
            }
          }
        ],
        series: series
      };
      let myChart = this.echarts.init(document.getElementById("a"));
      myChart.clear();
      myChart.setOption(option);

      // 空载损失系数map
      const option1 = {
        title: {
          text: "负载损失系数MAP"
        },
        tooltip: {
          trigger: "item",
          formatter: function(item) {
            let str = "";
            str += `挡位：${item.seriesName}<br/>转速：${item.data[0]}<br/>负载损失系数：${item.data[1]}`;
            str += "<br/><br/>";
            return str;
          }
        },
        legend: {
          x: "right",
          data: gearNames,
          textStyle: {
            fontsize: 5
          }
        },
        grid: {
          left: "10%",
          right: "4%",
          bottom: "8%",
          containLabel: true
        },

        xAxis: {
          type: "value",
          name: "输入转速(rpm)",
          nameLocation: "center",
          axisLine: { onZero: false },
          nameTextStyle: {
            padding: [0, 0, -25, 0],
            verticalAlign: "bottom"
          }
        },
        yAxis: [
          {
            name: "负载损失系数(%)",
            axisLine: {
              lineStyle: {
                color: "#102b6a"
              },
              show: true
            },
            type: "value",
            position: "left",
            splitLine: {
              show: false
            }
          }
        ],
        series: series1
      };
      let myChart1 = this.echarts.init(document.getElementById("b"));
      myChart1.clear();
      myChart1.setOption(option1);
    },

    /**
     * @desc 添加行数据
     */
    addRow() {
      const $table = this.$refs.xTable;
      const record = {
        gear: null,
        inputSpeed: null,
        unloadLoss: null,
        loadLossCoefficient: null,
        index: new Date().getTime()
      };
      this.tableData.push(record);
      const { row: newRow } = $table.insertAt(record, -1);
      this.findList();
      $table.setActiveCell(newRow, "gear");
      this.reRenderTable();
    },

    /**
     * @desc 删除行数据
     */
    async delRow() {
      debugger;
      const { rows } = await this.$refs.xTable.removeCheckboxRow();
      if (rows && rows.length > 0) {
        const newArr = [];
        const tempar = rows.map(item => item.index);
        this.tableData.forEach(item => {
          if (tempar.indexOf(item.index) == -1) {
            newArr.push(item);
          }
        });
        this.tableData = newArr;
        setTimeout(() => {
          this.renderEchart();
        }, 1000);
      } else {
        this.$Message.warning("没有可删除的数据！");
      }
    },

    saveData() {
      // 数据验证
      if (!(this.tableData && this.tableData.length > 0)) {
        this.$Message.warning("没有可保存的数据！");
        return;
      }
      // 挡位
      const gear = this.tableData.map(item => item.gear);
      // 输入转速(rpm)
      const inputSpeed = this.tableData.map(item => item.inputSpeed);
      // 空载损失(kW)
      const unloadLoss = this.tableData.map(item => item.unloadLoss);
      // 负载损失系数(%)
      const loadLossCoefficient = this.tableData.map(
        item => item.loadLossCoefficient
      );

      // 变速箱_id
      const gearboxId = this.gearboxId;

      const param = {
        gear: JSON.stringify(gear),
        inputSpeed: JSON.stringify(inputSpeed),
        unloadLoss: JSON.stringify(unloadLoss),
        loadLossCoefficient: JSON.stringify(loadLossCoefficient),
        tableData: JSON.stringify(this.tableData),
        gearboxId: gearboxId
      };
      gearboxEfficiencyApi.addGearboxEfficiency(param).then(res => {
        this.$Message.warning("保存成功");
      });
    },

    /**
     * 初始化列表数据
     */
    initData() {
      this.loading = true;
      gearboxEfficiencyApi
        .getByGearboxId(this.gearboxId)
        .then(res => {
          console.log("---->>>", res);
          const data = res.data;
          if (data) {
            // 组合table数据
            const tableData = JSON.parse(data.tableData);
            if (tableData && tableData.length > 0) {
              this.tableData = tableData;
              this.findList();
            } else {
              return;
            }
            this.renderEchart();
          }
        })
        .finally(() => {
          this.loading = false;
        });
    }
  }
};
</script>
